package com.binance.graceful.shutdown.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.binance.graceful.shutdown.core.GracefulShutdownTomcat;

import lombok.extern.log4j.Log4j2;

/**
 * Created by robin.wu on 2018/10/29.
 */
@Log4j2
@Configuration
@EnableConfigurationProperties(ShutdownProperties.class)
@ConditionalOnClass(value = org.apache.catalina.connector.Connector.class)
@ConditionalOnProperty(prefix = "container.graceful.shutdown", name = "enabled", havingValue = "true", matchIfMissing = false)
public class GracefulShutdownTomcatAutoConfiguration {

    @Bean
    @ConditionalOnClass(value=org.apache.catalina.connector.Connector.class)
    public GracefulShutdownTomcat gracefulShutdownTomcat(ShutdownProperties shutdownProperties) {
        return new GracefulShutdownTomcat(shutdownProperties.getWaitTime(),shutdownProperties.getAccessTime());
    }

    @Bean
    @ConditionalOnClass(value=org.apache.catalina.connector.Connector.class)
    public EmbeddedServletContainerCustomizer tomcatCustomizer(ShutdownProperties shutdownProperties) {
        return container -> {
            if (container instanceof TomcatEmbeddedServletContainerFactory) {
                ((TomcatEmbeddedServletContainerFactory) container)
                        .addConnectorCustomizers(gracefulShutdownTomcat(shutdownProperties));
            }
        };
    }


}
